package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"honeyweb/lib"
	"honeyweb/log"
	"honeyweb/middleware"
	"honeyweb/model"
	"net/http"
)

//以jsonrpc 结构请求的处理 模板
type RankController struct {
	HandlerMap map[string]lib.ClientHanlder
}

//创建 controller 和 初始化 方法名对应的处理函数 之间的关系
func NewRankController() *RankController {
	ct :=  &RankController{
		HandlerMap: make(map[string]lib.ClientHanlder),
	}

	//根据业务修改
	ct.HandlerMap["rank.goldRank"] = ct.GoldRank

	return ct
}

//添加本业务相关的中间件和 path
func RegisterRankRoute(group *gin.RouterGroup) {
	ct := NewRankController()
	rankGroup := group.Group("")
	rankGroup.Use(middleware.JWTAuth())
	rankGroup.POST("/rank",ct.HttpHandler)
}

//根据方法名找到对应的处理函数
func (ct *RankController)GetHandlerByMethod(method string) lib.ClientHanlder {
	handler, ok := ct.HandlerMap[method]
	if ok {
		return handler
	}
	return nil
}

//根据jsonrpc 的请求参数找到对应的处理函数处理
func (ct *RankController) HttpHandler(c *gin.Context) {
	var req model.JsonReq
	c.ShouldBindJSON(&req)
	uid := c.GetInt("uid")
	handler := ct.GetHandlerByMethod(req.Method)
	var resp *model.JsonResp
	if handler != nil {
		result, err := handler(uid,  &req)
		if err == nil {
			str := model.Encode2String(result)
			resp = model.NewResultResp(req.Id, req.Method, str)
		} else if err != nil{
			resp = model.NewErrJsonResp(req.Id,req.Method, model.E_SERVER, err.Error())
		}
	}
	c.JSON(http.StatusOK, resp)
}

//////////////////////////////////
///	//根据业务修改
/////////////////////////////////
func (ct *RankController) GoldRank(uid int, req *model.JsonReq) (interface{}, error){
	var params model.GoldRankReq
	model.DecodeFromString(req.Params, &params)
	log.S().Debugf("user: %d get goldrank: %+v", params )
	var resp model.GoldRankResp
	for i:=0; i< params.Num; i++ {
		u := model.GoldRankUser{
			Uid: i,
			Name: fmt.Sprintf("guest-%d",i),
			Rank:1,
			Gold: int64( 1000 +params.Num - i),
		}
		resp.List = append(resp.List, u)
	}
	return &resp, nil
}


